package bbs2.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bbs2.model.BoardAccessRule;

public class BoardAccessRuleDAO {
    
    private static BoardAccessRule makeBoardAccessRule(ResultSet rs) throws SQLException {
        BoardAccessRule boardAccessRule = new BoardAccessRule();
        boardAccessRule.setId(rs.getInt("ID"));
        boardAccessRule.setBoardId(rs.getInt("boardID"));
        boardAccessRule.setUserGroupId(rs.getInt("userGroupID"));
        boardAccessRule.setListArticles(rs.getBoolean("listArticles"));
        boardAccessRule.setCreateArticle(rs.getBoolean("createArticle"));
        boardAccessRule.setReadArticle(rs.getBoolean("readArticle"));
        boardAccessRule.setReadMyArticle(rs.getBoolean("readMyArticle"));
        boardAccessRule.setEditArticle(rs.getBoolean("editArticle"));
        boardAccessRule.setEditMyArticle(rs.getBoolean("editMyArticle"));
        boardAccessRule.setDeleteArticle(rs.getBoolean("deleteArticle"));
        boardAccessRule.setDeleteMyArticle(rs.getBoolean("deleteMyArticle"));
        boardAccessRule.setCreateComment(rs.getBoolean("createComment"));
        boardAccessRule.setManageBoard(rs.getBoolean("manageBoard"));
        return boardAccessRule;
    }

    public static BoardAccessRule selectByUserId(int boardId, int userId) throws Exception {
        BoardAccessRule board = null;
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;        
        try {
            connection = DB.getConnection();
            String sql = "EXEC boardAccessRuleSelectByUserId ?, ?"; 
            statement = connection.prepareStatement(sql);
            statement.setInt(1, boardId);
            statement.setInt(2, userId);
            resultSet = statement.executeQuery();
            if (resultSet.next()) board = makeBoardAccessRule(resultSet);
        } finally {
            if (resultSet != null) resultSet.close();
            if (statement != null) statement.close();
            if (connection != null) connection.close();
        }
        return board;
    }
}
